package com.example.handheld4_gsignal_app.ui.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.example.handheld4_gsignal_app.MainActivity;
import com.example.handheld4_gsignal_app.R;
import com.example.handheld4_gsignal_app.SignalCollectionActivity;
import com.example.handheld4_gsignal_app.services.SignalService;

/**
 * 实时监控Fragment - 显示当前信号状态和采集控制
 */
public class DashboardFragment extends Fragment {

    private TextView signalStrengthText;
    private TextView locationText;
    private TextView networkText;
    private TextView statusText;
    private Button collectionToggleButton;
    private Button reportButton;
    private SignalService signalService;
    
    // 数据采集状态跟踪
    private boolean hasSignalData = false;
    private boolean isCollecting = false;
    private boolean hasReportedData = false; // 新增：标记是否已上报过数据
    private int currentSignalStrength = 0;
    private String currentLocation = "";
    private String currentNetwork = "";

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_dashboard, container, false);
        
        initViews(view);
        setupClickListeners();
        initSignalService();
        
        return view;
    }

    /**
     * 初始化视图组件
     */
    private void initViews(View view) {
        signalStrengthText = view.findViewById(R.id.signal_strength_text);
        locationText = view.findViewById(R.id.location_text);
        networkText = view.findViewById(R.id.network_text);
        statusText = view.findViewById(R.id.status_text);
        collectionToggleButton = view.findViewById(R.id.collection_toggle_button);
        reportButton = view.findViewById(R.id.report_button);
    }

    /**
     * 设置点击事件监听器
     */
    private void setupClickListeners() {
        collectionToggleButton.setOnClickListener(v -> toggleSignalCollection());
        reportButton.setOnClickListener(v -> reportData());
    }

    /**
     * 初始化信号服务
     */
    private void initSignalService() {
        signalService = new SignalService(getContext());
        updateStatus("准备就绪");
        // 初始状态下上报按钮禁用，采集按钮显示"开始采集"
        updateReportButtonState();
        updateCollectionButtonState();
    }

    /**
     * 切换信号采集状态
     */
    private void toggleSignalCollection() {
        if (isCollecting) {
            stopSignalCollection();
        } else {
            startSignalCollection();
        }
    }

    /**
     * 开始信号采集
     */
    private void startSignalCollection() {
        if (signalService != null) {
            // 开始新的采集时重置数据状态
            hasSignalData = false;
            hasReportedData = false;
            currentSignalStrength = 0;
            currentLocation = "";
            currentNetwork = "";
            
            signalService.startCollection(new SignalService.SignalCallback() {
                @Override
                public void onSignalUpdate(int strength, String location, String network) {
                    updateSignalInfo(strength, location, network);
                }

                @Override
                public void onError(String error) {
                    updateStatus("错误: " + error);
                    Toast.makeText(getContext(), error, Toast.LENGTH_SHORT).show();
                }
            });
            updateStatus("正在采集...");
            isCollecting = true;
            updateCollectionButtonState();
            updateReportButtonState();
        }
    }

    /**
     * 停止信号采集
     */
    private void stopSignalCollection() {
        if (signalService != null) {
            signalService.stopCollection();
            isCollecting = false;
            updateCollectionButtonState();
            
            // 停止采集后检查是否有有效数据
            if (hasSignalData && currentSignalStrength != 0) {
                updateStatus("采集完成，数据已就绪");
                // 重置上报状态，允许上报新采集的数据
                hasReportedData = false;
                updateReportButtonState();
            } else {
                updateStatus("采集完成，但未获取到有效数据");
                hasSignalData = false;
                updateReportButtonState();
            }
        }
    }

    /**
     * 更新采集按钮状态和文本
     */
    private void updateCollectionButtonState() {
        if (getActivity() != null) {
            getActivity().runOnUiThread(() -> {
                if (isCollecting) {
                    // 正在采集时显示"停止采集"
                    collectionToggleButton.setText("⏹️ 停止采集");
                    collectionToggleButton.setTextAppearance(R.style.SecondaryButton);
                } else {
                    // 未采集时显示"开始采集"
                    collectionToggleButton.setText("▶️ 开始采集");
                    collectionToggleButton.setTextAppearance(R.style.PrimaryButton);
                }
            });
        }
    }

    /**
     * 更新信号信息显示
     */
    private void updateSignalInfo(int strength, String location, String network) {
        if (getActivity() != null) {
            getActivity().runOnUiThread(() -> {
                signalStrengthText.setText("信号强度: " + strength + " dBm");
                locationText.setText("位置: " + location);
                networkText.setText("网络: " + network);
                
                // 更新数据状态
                currentSignalStrength = strength;
                currentLocation = location;
                currentNetwork = network;
                hasSignalData = true;
                
                // 更新上报按钮状态
                updateReportButtonState();
            });
        }
    }

    /**
     * 更新状态显示
     */
    private void updateStatus(String status) {
        if (getActivity() != null) {
            getActivity().runOnUiThread(() -> {
                statusText.setText("状态: " + status);
            });
        }
    }

    /**
     * 更新上报按钮状态
     */
    private void updateReportButtonState() {
        if (getActivity() != null) {
            getActivity().runOnUiThread(() -> {
                if (hasSignalData && !hasReportedData && !isCollecting) {
                    // 有数据且未上报过且不在采集状态时启用按钮
                    reportButton.setEnabled(true);
                    reportButton.setText("📤 上报数据");
                    reportButton.setBackgroundResource(R.drawable.button_report);
                    reportButton.setTextColor(getResources().getColor(R.color.text_white));
                } else if (hasReportedData) {
                    // 已上报过数据时禁用按钮
                    reportButton.setEnabled(false);
                    reportButton.setText("📤 已上报");
                    reportButton.setBackgroundResource(R.drawable.button_report_disabled);
                    reportButton.setTextColor(getResources().getColor(R.color.text_tertiary));
                } else if (isCollecting) {
                    // 正在采集时禁用按钮
                    reportButton.setEnabled(false);
                    reportButton.setText("📤 采集中...");
                    reportButton.setBackgroundResource(R.drawable.button_report_disabled);
                    reportButton.setTextColor(getResources().getColor(R.color.text_tertiary));
                } else {
                    // 无数据时禁用按钮
                    reportButton.setEnabled(false);
                    reportButton.setText("📤 上报 (无数据)");
                    reportButton.setBackgroundResource(R.drawable.button_report_disabled);
                    reportButton.setTextColor(getResources().getColor(R.color.text_tertiary));
                }
            });
        }
    }

    /**
     * 上报数据
     */
    private void reportData() {
        // 检查是否有数据可上报
        if (!hasSignalData) {
            Toast.makeText(getContext(), "没有可上报的数据，请先采集信号", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 检查是否已经上报过
        if (hasReportedData) {
            Toast.makeText(getContext(), "数据已上报，请重新采集后再上报", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 检查是否正在采集
        if (isCollecting) {
            Toast.makeText(getContext(), "请先停止采集再进行上报", Toast.LENGTH_SHORT).show();
            return;
        }
        
        if (signalService != null) {
            // 显示加载状态
            showReportLoadingState();
            
            // 获取当前信号数据
            String currentSignal = signalStrengthText.getText().toString();
            String currentLocation = locationText.getText().toString();
            String currentNetwork = networkText.getText().toString();
            
            // 模拟数据上报
            signalService.reportData(new SignalService.ReportCallback() {
                @Override
                public void onReportSuccess() {
                    if (getActivity() != null) {
                        getActivity().runOnUiThread(() -> {
                            Toast.makeText(getContext(), "数据上报成功", Toast.LENGTH_SHORT).show();
                            updateStatus("数据已上报");
                            // 标记数据已上报，按钮变为不可用状态
                            hasReportedData = true;
                            updateReportButtonState();
                        });
                    }
                }

                @Override
                public void onReportError(String error) {
                    if (getActivity() != null) {
                        getActivity().runOnUiThread(() -> {
                            Toast.makeText(getContext(), "上报失败: " + error, Toast.LENGTH_SHORT).show();
                            updateStatus("上报失败");
                            // 上报失败时保持按钮可用状态，允许重试
                            updateReportButtonState();
                        });
                    }
                }
            });
            
            updateStatus("正在上报...");
        } else {
            Toast.makeText(getContext(), "信号服务未初始化", Toast.LENGTH_SHORT).show();
        }
    }
    
    /**
     * 显示上报加载状态
     */
    private void showReportLoadingState() {
        if (getActivity() != null) {
            getActivity().runOnUiThread(() -> {
                reportButton.setEnabled(false);
                reportButton.setText("⏳ 上报中...");
                reportButton.setBackgroundResource(R.drawable.button_report_loading);
                reportButton.setTextColor(getResources().getColor(R.color.text_white));
            });
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (signalService != null) {
            signalService.stopCollection();
        }
    }
}